package com.FH.organization.notice;


import com.FH.applyForm.officeServies.notice_type.NoticeTypeResource;
import com.FH.applyForm.officeServies.noticemember.NoticeMemberPullDTO;
import com.FH.applyForm.officeServies.noticemember.NoticeMemberResource;
import com.FH.organization.Attachment.AttachmentResource;
import com.FH.organization.department.DepartmentResource;
import com.FH.organization.operator_log.OperatorLogPullDTO;
import com.FH.organization.operator_log.OperatorLogResource;
import com.FH.organization.people.KamMemberIdName;
import com.FH.organization.people.KamMemberResource;
import com.FH.organization.people.KamMemberShowDTO;
import com.FH.organization.remind.RemindPullDTO;
import com.FH.organization.remind.RemindResource;
import com.FH.organization.suggestion.SuggestionResource;
import com.FH.organization.work_flow.WorkFlowPullDTO;
import com.FH.organization.work_flow.WorkFlowResource;
import com.FH.permission.sys_role.SysroleResource;
import com.FH.util.*;
import com.itextpdf.text.DocumentException;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import javax.ejb.Stateless;
import javax.inject.Inject;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by WLB on 2016/7/21.
 * <p>
 * 公告管理实现类
 */
@Stateless
public class NoticeDAOImpl extends AccessDB implements NoticeDAO {
    @Inject
    SuggestionResource suggestionResource;
    @Inject
    NoticeMemberResource noticeMemberResource;

    @Inject
    WorkFlowResource workFlowResource;

    @Inject
    AttachmentResource attachmentResource;

    @Inject
    DepartmentResource departmentResource;

    @Inject
    SysroleResource sysroleResource;
    @Inject
    NoticeTypeResource noticeTypeResource;

    @Inject
    RemindResource remindResource;

    @Inject
    KamMemberResource kamMemberResource;
    @Inject
    OperatorLogResource operatorLogResource;

    /**
     * 查询消息通知实现类
     *
     * @param serach
     * @param page
     * @param size
     * @return
     */
    @Override
    public ResultDTO getNoticeInfo(String serach, String page, String size) {
        ResultDTO resultDTO = new ResultDTO();

        try {
            JSONObject json = new JSONObject(serach);
            String existName = "0";

            String sqlexit = "select count(1) from notice  where 1=1 ";

            String sql_w = "";//查询条件sql组合
            String sql_page = "";//分页组合

            Integer page_ok = Integer.parseInt(page);//将定义page、size的String类型转换成Integer类型
            Integer size_ok = Integer.parseInt(size);

            if (page.equals("1")) {
                sql_page = " limit 0," + size + "";
            } else {
                sql_page = " limit " + ((page_ok - 1) * size_ok + 1) + "," + size + "";
            }

            if (json.has("member_id")) {
                sql_w += " AND member_id = '" + json.getString("member_id") + "'";
            }
            if (json.has("notice_member")) {
                sql_w += " AND notice_member = '" + json.getString("notice_member") + "'";
            }
            if (json.has("notice_id")) {
                sql_w += " AND notice_id = '" + json.getString("notice_id") + "'";
            }
            if (json.has("notice_title")) {
                sql_w += " AND notice_title = '" + json.getString("notice_title") + "'";
            }
            if (json.has("istop")) {
                sql_w += " AND istop = '" + json.getString("istop") + "'";
            }
//            if(json.has("isverify")){
//                sql_w += " AND isverify ='" + json.getString("isverify")+"'";
//            }else{
//                sql_w += " AND (isverify IS NULL OR isverify=0)";
//            }


            String sql_ok = sqlexit + sql_w + sql_page;//组合好的sql语句
            existName = getReportingToOne(sql_ok);

            List<String[]> seresult = new ArrayList<String[]>();

            List<NoticeShowDTO> result = new ArrayList<NoticeShowDTO>();

            if (!existName.equals("0")) {
                String sqlq = "select notice_id,notice_title,notice_type_id,rangeorganization_id,notice_starttime," +
                        "issendnotify,istop,notice_toptime,attachment_id,notice_main,notice_html,notice_createtime,notice_updatetime,sys_role_id,notice_endtime,member_id,notice_types,fail_resource FROM notice where 1=1  " + sql_w +" ORDER BY notice_createtime DESC "+ sql_page;

                seresult = this.getReportingTo(sqlq);

                //构建返回对象
                for (int i = 0; i < seresult.size(); i++) {
                    NoticeShowDTO noticeShowDTO = new NoticeShowDTO();
                    noticeShowDTO.setNotice_id(seresult.get(i)[1]);
                    noticeShowDTO.setNotice_title(seresult.get(i)[2]);
                    noticeShowDTO.setNotice_type(seresult.get(i)[3]);
                    noticeShowDTO.setRangeorganization_id(seresult.get(i)[4]);
                    noticeShowDTO.setNotice_starttime(seresult.get(i)[5]);
                    noticeShowDTO.setIssendnotify(seresult.get(i)[6]);
                    noticeShowDTO.setIstop(seresult.get(i)[7]);
                    noticeShowDTO.setNotice_toptime(seresult.get(i)[8]);
                    noticeShowDTO.setAttachment_id(seresult.get(i)[9]);
                    noticeShowDTO.setNotice_main(seresult.get(i)[10]);
                    noticeShowDTO.setNotice_html(seresult.get(i)[11]);
                    noticeShowDTO.setNotice_createtime(seresult.get(i)[12]);
                    noticeShowDTO.setNotice_updatetime(seresult.get(i)[13]);
                    noticeShowDTO.setSys_role_id(seresult.get(i)[14]);
                    noticeShowDTO.setNotice_endtime(seresult.get(i)[15]);
                    noticeShowDTO.setMember_id(seresult.get(i)[16]);
                    noticeShowDTO.setNotice_types(seresult.get(i)[17]);
                    noticeShowDTO.setFail_resource(seresult.get(i)[18]);
                    noticeShowDTO.setIndexnumber(String.valueOf(i+1));

                    ResultDTO jsonpeople = null, organization = null, sysrole = null, attachment = null, noticeTypeinfo = null,suggestion=null;

                    /**
                     * 返回公告类型
                     */
                    if (null != seresult.get(i)[3] && !"".equals(seresult.get(i)[3])) {
                        noticeTypeinfo = noticeTypeResource.getNoticeTypeInfo("{id:" + seresult.get(i)[3] + "}", "1", "1");

                        noticeShowDTO.setNotice_type_info(noticeTypeinfo.getValues());
                    }

                    /**
                     * 根据单据id查出人员信息
                     */
                    if (null != seresult.get(i)[1] && !"".equals(seresult.get(i)[1])) {
                        jsonpeople = noticeMemberResource.getNoticeMemberInfo("{notice_id:" + seresult.get(i)[1] + ",notice_type:" + seresult.get(i)[17] + "}", "1", "10000");
                        noticeShowDTO.setQq(jsonpeople.getValues());
                    }

                    /**
                     * 根据部门id查出具体信息
                     */
                    if (null != seresult.get(i)[4] && !"".equals(seresult.get(i)[4])) {
                        organization = departmentResource.getDepartmentInfo("{organization_id:" + seresult.get(i)[4] + "}", "1", "1");
                        noticeShowDTO.setDepartmentlist(organization.getValues());
                    }
                    /**
                     * 根据角色id 查出具体信息
                     */
                    if (null != seresult.get(i)[14] && !"".equals(seresult.get(i)[14])) {
                        sysrole = sysroleResource.getSysroleInfo("{sys_role_id:" + seresult.get(i)[14] + "}", "1", "1");
                        noticeShowDTO.setSysrolelist(sysrole.getValues());
                    }

                    /**
                     * 根据附件id 查出具体附件信息
                     */
                    if (null != seresult.get(i)[9] && !"".equals(seresult.get(i)[9])) {
                        attachment = attachmentResource.getAttachmentInfo("{attachment_id:" + seresult.get(i)[9] + "}", "1", "1");
                        noticeShowDTO.setAttachmentlist(attachment.getValues());
                    }
                    if(seresult.get(i)[1] != null && ! seresult.get(i)[1].equals("")){

                        suggestion=suggestionResource.getSuggestionInfo("{form_id:" + seresult.get(i)[1] + "}", "1", "100");
                        noticeShowDTO.setSuggestionShowDTOs(suggestion.getValues());
                    }
                    result.add(noticeShowDTO);

                }
            }
            if (seresult.size() != 0) {
                resultDTO.setStr(result.size() + "");
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion(warnSrc.get_success);
                resultDTO.setValues(result);
            } else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion(warnSrc.get_fail);
            }

        } catch (JSONException e) {
            e.printStackTrace();

        }
        return resultDTO;
    }

    /**
     * 收到的公告
     * @param search
     * @param page
     * @param size
     * @return
     */

    @Override
    public ResultDTO getNoticeTitle(String search, String page, String size) {
        ResultDTO resultDTO = new ResultDTO();

        String sql = "SELECT n.notice_id,n.notice_title,n.notice_main,n.notice_createtime FROM notice_member nm " +
                "LEFT JOIN notice n " +
                "ON n.notice_id = nm.notice_id " +
                "WHERE  1=1 ";

        String downloadUrl = "";
        String pdfDownLoadUrl = "";
        try {
            JSONObject jsonObject = new JSONObject(search);

            Integer page_ok = Integer.parseInt(page);//将定义page、size的String类型转换成Integer类型
            Integer size_ok = Integer.parseInt(size);

            if(jsonObject.has("member_id")){
                if(!jsonObject.get("member_id").toString().isEmpty()){
                    sql += "AND nm.member_id = '" + jsonObject.get("member_id").toString() + "' ";
                }
            }

            if(jsonObject.has("starttime")){
                if(!jsonObject.get("starttime").toString().isEmpty()){
                    sql += "and n.notice_createtime > '" + jsonObject.get("starttime").toString() + "' ";
                }
            }

            if(jsonObject.has("endtime")){
                if(!jsonObject.get("endtime").toString().isEmpty()){
                    sql += "and n.notice_createtime < '" + jsonObject.get("endtime").toString() + "' ";
                }
            }


            if(jsonObject.has("export")){
                if(!jsonObject.get("export").equals("1")){
                    if (page.equals("1")) {
                        sql += " limit 0," + size + "";
                    } else {
                        sql += " limit " + ((page_ok - 1) * size_ok + 1) + "," + size + "";
                    }
                }
            }
            else{
                if (page.equals("1")) {
                    sql += " limit 0," + size + "";
                } else {
                    sql += " limit " + ((page_ok - 1) * size_ok + 1) + "," + size + "";
                }
            }


            List<String[]> seresult = new ArrayList<String[]>();

            List<NoticeOtherShowDTO> result = new ArrayList<NoticeOtherShowDTO>();

            seresult = this.getReportingTo(sql);

            for(int i=0;i<seresult.size();i++){
                NoticeOtherShowDTO noticeOtherShowDTO = new NoticeOtherShowDTO();
                noticeOtherShowDTO.setNotice_id(seresult.get(i)[1] == null ? "" :seresult.get(i)[1] );
                noticeOtherShowDTO.setNotice_title(seresult.get(i)[2] == null ? "":seresult.get(i)[2] );
                noticeOtherShowDTO.setNotice_main(seresult.get(i)[3] == null ? "":seresult.get(i)[3]);
                noticeOtherShowDTO.setNotice_createtime(seresult.get(i)[4] == null ? "":seresult.get(i)[4]);
                result.add(noticeOtherShowDTO);
            }

            if(jsonObject.has("export")){
                if(jsonObject.get("export").equals("1")){
                    String[] headers = {"公告id", "公告标题", "公告内容","公告创建时间"};
                    String title = "公告统计";
                    String filename = "公告统计表";//+ df.format(new Date())

                    ExportExcel<NoticeOtherShowDTO> exportExcel = new ExportExcel<NoticeOtherShowDTO>();
                    downloadUrl = exportExcel.createExcelFile(exportExcel, title, headers, result, filename);
                    try {
                        pdfDownLoadUrl = ExportPDF.createPDFFile(seresult, title, headers, filename);
                    } catch (DocumentException e) {
                        e.printStackTrace();
                    }
                }
            }

            if (seresult.size() != 0) {
                resultDTO.setStr(pdfDownLoadUrl);
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion(downloadUrl);
                resultDTO.setValues(result);
            } else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion(warnSrc.get_fail);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return resultDTO;
    }


    /**
     * 修改字段信息（不删除公告类型表）
     *
     * @param noticePullDTO
     * @return
     */
    @Override
    public ResultDTO updateNoticeOtherInfo(NoticePullDTO noticePullDTO) {
        ResultDTO resultDTO = new ResultDTO();

        String QUERY = "";

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());

        //更新sql语句
        QUERY += "update notice set notice_updatetime ='" + time + "'";
        if (null != noticePullDTO.getNotice_title() && !"".equals(noticePullDTO.getNotice_title())) {
            QUERY += ", notice_title = '" + noticePullDTO.getNotice_title() + "'";
        }

        if (null != noticePullDTO.getNotice_type_id() && !"".equals(noticePullDTO.getNotice_type_id())) {
            QUERY += ",notice_type_id ='" + noticePullDTO.getNotice_type_id() + "'";
        }

        if (null != noticePullDTO.getRangeorganization_id() && !"".equals(noticePullDTO.getRangeorganization_id())) {
            QUERY += ",rangeorganization_id ='" + noticePullDTO.getRangeorganization_id() + "'";
        }

        if (null != noticePullDTO.getNotice_starttime() && !"".equals(noticePullDTO.getNotice_starttime())) {
            QUERY += ",notice_starttime ='" + noticePullDTO.getNotice_starttime() + "'";
        }
        if (null != noticePullDTO.getNotice_endtime() && !"".equals(noticePullDTO.getNotice_endtime())) {
            QUERY += ",notice_endtime ='" + noticePullDTO.getNotice_endtime() + "'";
        }

        if (null != noticePullDTO.getIssendnotify() && !"".equals(noticePullDTO.getIssendnotify())) {
            QUERY += ",issendnotify ='" + noticePullDTO.getIssendnotify() + "'";
        }
        if (null != noticePullDTO.getIstop() && !"".equals(noticePullDTO.getIstop())) {
            QUERY += ",istop ='" + noticePullDTO.getIstop() + "'";
        }

        if (null != noticePullDTO.getNotice_toptime() && !"".equals(noticePullDTO.getNotice_toptime())) {
            QUERY += ",notice_toptime ='" + noticePullDTO.getNotice_toptime() + "'";
        }
        if (null != noticePullDTO.getAttachment_id() && !"".equals(noticePullDTO.getAttachment_id()) && null != noticePullDTO.getFilestream() && !"".equals(noticePullDTO.getFilestream())) {
            //调用修改文件方法
            updateImage(noticePullDTO);
        } else if (null != noticePullDTO.getFilestream() && !"".equals(noticePullDTO.getFilestream())) {
            String uid = getImage(noticePullDTO)[0];
            QUERY += ",attachment_id='" + uid + "'";

        }
        if (null != noticePullDTO.getNotice_main() && !"".equals(noticePullDTO.getNotice_main())) {
            QUERY += ",notice_main ='" + noticePullDTO.getNotice_main() + "'";
        }
        if (null != noticePullDTO.getNotice_html() && !"".equals(noticePullDTO.getNotice_html())) {
            String html = replaceimage(noticePullDTO);

            QUERY += ",notice_html ='" + html + "'";
        }
        if (null != noticePullDTO.getSys_role_id() && !"".equals(noticePullDTO.getSys_role_id())) {
            QUERY += ",sys_role_id ='" + noticePullDTO.getSys_role_id() + "'";
        }
        if (null != noticePullDTO.getNotice_types() && !"".equals(noticePullDTO.getNotice_types())) {
            QUERY += ",notice_types ='" + noticePullDTO.getNotice_types() + "'";
        }
        if (null != noticePullDTO.getFail_resource() && !"".equals(noticePullDTO.getFail_resource())) {
            QUERY += ",fail_resource ='" + noticePullDTO.getFail_resource() + "'";
        }

        QUERY += " where notice_id = '" + noticePullDTO.getNotice_id() + "'";


        int result = this.addReportingTo(QUERY);
        // 判断SQl是否执行成功
        if (result != 0) {
            resultDTO.setStr(noticePullDTO.getNotice_id());
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.update_success);
        } else {
            resultDTO.setStatus("90001");
        }
        return resultDTO;
    }


    /**
     * 添加公告通知
     *
     * @param noticePullDTO
     * @return
     */
    @Override
    public ResultDTO addNoticeInfo(NoticePullDTO noticePullDTO) {

        ResultDTO resultDTO = new ResultDTO();//构建返回对象

        String issendnotify = noticePullDTO.getIssendnotify();

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());

        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

        String existName = "";
        String notice_id = noticePullDTO.getNotice_id();
        if (notice_id != null && !notice_id.equals("")) {

            String sql = "select count(1) from notice where notice_id='" + notice_id + "'";

            existName = getReportingToOne(sql);

            if (!existName.equals("0")) {
                return updateNoticeInfo(noticePullDTO);
            }
        }


        String uid = "";
        if (null != noticePullDTO.getFile_type() && !"".equals(noticePullDTO.getFile_type())) {
            uid = getImage(noticePullDTO)[0];
        }

        if (null != noticePullDTO.getNotice_html() && !"".equals(noticePullDTO.getNotice_html())) {
            String html = replaceimage(noticePullDTO);
            noticePullDTO.setNotice_html(html);
        }
        /**
         * 判断前端传过来的集合是什么
         */
        //  if(noticePullDTO.getNotice_types()!=null&&!"".equals(noticePullDTO.getNotice_types())){

        /**
         * 按部门发布
         */
        String rangeorganization_id = "";
        if (noticePullDTO.getRangeorganization_id() != null && !"".equals(noticePullDTO.getRangeorganization_id()) && noticePullDTO.getNotice_types().equals("1")) {


            rangeorganization_id = noticePullDTO.getRangeorganization_id();
        }


//        /**
//         * 按角色发布
//         */
//
//        String sys_role_id = "";
//        if (noticePullDTO.getSys_role_id() != null && !"".equals(noticePullDTO.getSys_role_id()) && noticePullDTO.getNotice_types().equals("2")) {
//
//            sys_role_id = noticePullDTO.getSys_role_id();
//        }

        //全部门发送
        String sys_role_id = "";
        if (noticePullDTO.getNotice_types().equals("2")) {

            sys_role_id = noticePullDTO.getSys_role_id();
        }


        String QUERY = "";

        //表中查看时间设为空值
        QUERY += "insert into notice(notice_id,member_id,notice_title,notice_type_id,notice_starttime," +
                "issendnotify,istop,notice_toptime,attachment_id,notice_main,notice_html,notice_createtime,notice_updatetime,rangeorganization_id ,sys_role_id,notice_types,notice_endtime,fail_resource) values" +
                " ('" + uuid + "','" + noticePullDTO.getMember_id() + "','" + noticePullDTO.getNotice_title() + "','" + noticePullDTO.getNotice_type_id() + "','"
                + noticePullDTO.getNotice_starttime() + "','" + noticePullDTO.getIssendnotify() + "','" + noticePullDTO.getIstop() + "'," +
                "'" + noticePullDTO.getNotice_toptime() + "','" + uid + "','" + noticePullDTO.getNotice_main() + "','" + noticePullDTO.getNotice_html() + "','" + time + "','" + " " + "','" + rangeorganization_id + "','" + sys_role_id + "','" + noticePullDTO.getNotice_types() + "','" + noticePullDTO.getNotice_endtime() + "','" + " " + "')";
        int result = this.addReportingTo(QUERY);
        // 判断SQl是否执行成功
        if (result != 0) {

            if(noticePullDTO.getNotice_types().equals("1")){
                /**
                 * 计算提醒开始时间
                 */
                try {
                    /**
                     * 按部门提醒
                     *
                     * 查出该部门下所有人
                     */
                    String rangeorganization_id1 = "";
                    if (noticePullDTO.getRangeorganization_id() != null && !"".equals(noticePullDTO.getRangeorganization_id()) && null != issendnotify && issendnotify.equals("1")) {
                        ResultDTO userlist = null;
                        rangeorganization_id1 = noticePullDTO.getRangeorganization_id();
                        userlist = kamMemberResource.getUserListInfo("{organization_id:" + rangeorganization_id1 + "}", "1", "20");
                        ArrayList<KamMemberShowDTO> mens = (ArrayList<KamMemberShowDTO>) userlist.getValues();// List集合  强转
                        for (int i = 0; i < mens.size(); i++) {
                            KamMemberShowDTO kamMemberShowDTO = mens.get(i);

                            /**
                             * 部门下的所有提醒人
                             */

                            NoticeMemberPullDTO noticeMemberPullDTO = new NoticeMemberPullDTO();
                            noticeMemberPullDTO.setNotice_id(uuid);
                            noticeMemberPullDTO.setMember_id(kamMemberShowDTO.getMember_id());
                            noticeMemberPullDTO.setMember_name(kamMemberShowDTO.getMember_name());
                            noticeMemberPullDTO.setNotice_type(noticePullDTO.getNotice_types());
                            noticeMemberPullDTO.setIsread("0");
                            noticeMemberResource.addNoticeMemberInfo(noticeMemberPullDTO);

                            /**
                             * 事物提醒
                             */
                            RemindPullDTO remindPullDTO = new RemindPullDTO();
                            remindPullDTO.setRemind_content(noticePullDTO.getNotice_title());
                            remindPullDTO.setRemind_time(noticePullDTO.getNotice_starttime());
                            remindPullDTO.setRemind_type("9");
                            remindPullDTO.setRemind_form_id(uuid);
                            remindPullDTO.setRemind_order("0");
                            remindPullDTO.setCreate_time(time);
                            remindPullDTO.setRemind_endtime(noticePullDTO.getNotice_endtime());
                            remindPullDTO.setRemind_member_id(kamMemberShowDTO.getMember_id());
                            remindPullDTO.setRemind_starttime(noticePullDTO.getNotice_starttime());
                            remindPullDTO.setRemind_descritpion("您有一条新的公告，请注意查收！");
                            remindResource.addRemindInfo(remindPullDTO);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }else if(noticePullDTO.getNotice_types().equals("3")){
                /**
                 *按人员发布，所有人的集合
                 */
                if (noticePullDTO.getNoticemember() != null && !"".equals(noticePullDTO.getNoticemember()) && noticePullDTO.getNotice_types().equals("3")) {


                    String noticemember = noticePullDTO.getNoticemember();
                    try {
                        JSONArray array = new JSONArray(noticemember);
                        if (array != null && array.length() > 0) {
                            List<NoticePullDTO> result1 = new ArrayList<NoticePullDTO>();
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject jsonObject = array.getJSONObject(i);
                                String id = jsonObject.getString("id");
                                String name = jsonObject.getString("name");
                                NoticeMemberPullDTO noticeMemberPullDTO = new NoticeMemberPullDTO();
                                noticeMemberPullDTO.setNotice_id(uuid);
                                noticeMemberPullDTO.setMember_id(id);
                                noticeMemberPullDTO.setMember_name(name);
                                noticeMemberPullDTO.setNotice_type(noticePullDTO.getNotice_types());
                                noticeMemberPullDTO.setIsread("0");
                                noticeMemberResource.addNoticeMemberInfo(noticeMemberPullDTO);

                                /**
                                 * 事物提醒
                                 */
                                RemindPullDTO remindPullDTO = new RemindPullDTO();
                                remindPullDTO.setRemind_content(noticePullDTO.getNotice_title());
                                remindPullDTO.setRemind_time(noticePullDTO.getNotice_starttime());
                                remindPullDTO.setRemind_type("9");
                                remindPullDTO.setRemind_form_id(uuid);
                                remindPullDTO.setRemind_order("0");
                                remindPullDTO.setCreate_time(time);
                                remindPullDTO.setRemind_endtime(noticePullDTO.getNotice_endtime());
                                remindPullDTO.setRemind_member_id(id);
                                remindPullDTO.setRemind_starttime(noticePullDTO.getNotice_starttime());
                                remindPullDTO.setRemind_descritpion("您有一条新的公告，请注意查收！");
                                remindResource.addRemindInfo(remindPullDTO);
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

            }

            //按所有人员发布
            if (noticePullDTO.getNotice_types().equals("2")){
                List<KamMemberIdName> listMember = kamMemberResource.getAllMemberIdName();
                for(int i =0 ;i<listMember.size();i++){
                    KamMemberIdName kamMemberIdName = listMember.get(i);

                    /**
                     * 部门下的所有提醒人
                     */

                    NoticeMemberPullDTO noticeMemberPullDTO = new NoticeMemberPullDTO();
                    noticeMemberPullDTO.setNotice_id(uuid);
                    noticeMemberPullDTO.setMember_id(kamMemberIdName.getMember_id());
                    noticeMemberPullDTO.setMember_name(kamMemberIdName.getMember_name());
                    noticeMemberPullDTO.setNotice_type(noticePullDTO.getNotice_types());
                    noticeMemberPullDTO.setIsread("0");
                    noticeMemberResource.addNoticeMemberInfo(noticeMemberPullDTO);

                    /**
                     * 事物提醒
                     */
                    RemindPullDTO remindPullDTO = new RemindPullDTO();
                    remindPullDTO.setRemind_content(noticePullDTO.getNotice_title());
                    remindPullDTO.setRemind_time(noticePullDTO.getNotice_starttime());
                    remindPullDTO.setRemind_type("9");
                    remindPullDTO.setRemind_form_id(uuid);
                    remindPullDTO.setRemind_order("0");
                    remindPullDTO.setCreate_time(time);
                    remindPullDTO.setRemind_endtime(noticePullDTO.getNotice_endtime());
                    remindPullDTO.setRemind_member_id(kamMemberIdName.getMember_id());
                    remindPullDTO.setRemind_starttime(noticePullDTO.getNotice_starttime());
                    remindPullDTO.setRemind_descritpion("您有一条新的公告，请注意查收！");
                    remindResource.addRemindInfo(remindPullDTO);

                }
            }



//
//            WorkFlowPullDTO workFlowPullDTO = new WorkFlowPullDTO();
//            workFlowPullDTO.setWork_flow_formid(uuid);
//            workFlowPullDTO.setWork_flow_type("notice");
//            workFlowPullDTO.setWork_flow_desc("公告申请请求审批");
//            workFlowPullDTO.setWork_flow_date(time);
//            workFlowPullDTO.setWork_flow_order("0");
//            workFlowPullDTO.setWork_flow_createid(noticePullDTO.getMember_id());
//            workFlowPullDTO.setWork_flow_approval(noticePullDTO.getReport_people());
//            workFlowPullDTO.setWork_flow_approval_organization_id(noticePullDTO.getWork_flow_approval_organization_id());
//            workFlowPullDTO.setFlow_path_id(noticePullDTO.getFlow_path_id());
//            workFlowPullDTO.setWork_flow_suggestion("");
//            workFlowResource.addWorkFlowInfo(workFlowPullDTO);
            //日志操作
            OperatorLogPullDTO operatorlogPullDTO = new OperatorLogPullDTO();
            operatorlogPullDTO.setOperator_log_title(noticePullDTO.getNotice_title());
            operatorlogPullDTO.setOperator_log_content(noticePullDTO.getNotice_main());
            operatorlogPullDTO.setMember_id(noticePullDTO.getMember_id());
            operatorLogResource.addOperatorLogInfo(operatorlogPullDTO);
            resultDTO.setStr(uuid);
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.add_success);

        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.add_fail);
        }
        return resultDTO;
    }


    public String replaceimage(NoticePullDTO noticePullDTO) {
        String content = "<p><span>这是内容开始</span><br />"
                + "<img src=\"http://localhost:8080/uploadFile/video/1111111111.mp4\"/><br/>"
                + "<span>这是内容中间</span><br/>"
                + "<img src=\"http://localhost:8080/uploadFile/video/2222222222.mp4\"/><br/>"
                + "<span>这是内容结尾</span></p>";

        String regxpForEmbedTag = "<\\s*img\\s+([^>]*)\\s*>";
        Matcher matcher = Pattern.compile(regxpForEmbedTag).matcher(noticePullDTO.getNotice_html());
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String contentTemp = matcher.group(1);
            String contentTemp0 = matcher.group(0);
            String src = getImgStr(contentTemp0).get(0);
            String str[] = src.split(",");
            if (str != null && str.length > 1) {
                String filebase1 = str[1];
//                String filebase2[] = filebase1.split(",");
//                String filebase3 = filebase2[1];
                String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
                noticePullDTO.setFilestream(filebase1);
                noticePullDTO.setFile_type(uuid + ".jpg");
                noticePullDTO.setFile_name(uuid + ".jpg");
                String imagebase64 = getImage(noticePullDTO)[1];

                contentTemp = replaceContentByPartten(contentTemp,
                        "src=\"([^\"]+)\"", "src=\"" + imagebase64 + "\"");
                matcher.appendReplacement(sb, "<img " + contentTemp + ">");
                matcher.appendTail(sb);
            }
        }
        return !sb.toString().equals("") ? sb.toString() : noticePullDTO.getNotice_html();
    }

    /**
     * 得到网页中图片的地址
     */
    public static List<String> getImgStr(String htmlStr) {
        List<String> pics = new ArrayList<String>();
        String img = "";
        Pattern p_image;
        Matcher m_image;
        //     String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile
                (regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            // 得到<img />数据
            img = m_image.group();
            // 匹配<img>中的src数据
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                pics.add(m.group(1));
            }
        }
        return pics;
    }


    public static String replaceContentByPartten(String content, String partten, String target) {
        Matcher matcher = Pattern.compile(partten, Pattern.CASE_INSENSITIVE).matcher(content);
        if (matcher.find()) {
            StringBuffer temp = new StringBuffer();
            matcher.appendReplacement(temp, target);
            matcher.appendTail(temp);
            return temp.toString();
        } else {
            return content;
        }
    }


    /**
     * 修改公告通知
     *
     * @param noticePullDTO
     * @return
     */
    @Override
    public ResultDTO updateNoticeInfo(NoticePullDTO noticePullDTO) {

        /**
         * 要修改  先删除
         */
        ResultDTO resultss = null;
        String notice_id = noticePullDTO.getNotice_id();
        NoticeMemberPullDTO noticeMemberPullDTO = new NoticeMemberPullDTO();
        noticeMemberPullDTO.setNotice_id(notice_id);
        noticeMemberResource.deleteNoticeMemberInfo(noticeMemberPullDTO);
        //  if(resultss!=null){
        if (null != noticePullDTO.getNoticemember() && !"".equals(noticePullDTO.getNoticemember())) {
            String noticemember = noticePullDTO.getNoticemember();
            try {
                JSONArray array = new JSONArray(noticemember);
                if (array != null && array.length() > 0) {
                    List<NoticePullDTO> result = new ArrayList<NoticePullDTO>();
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject jsonObject = array.getJSONObject(i);
                        String id = jsonObject.getString("id");
                        String name = jsonObject.getString("name");
                        NoticeMemberPullDTO noticeMemberPullDTO1 = new NoticeMemberPullDTO();
                        noticeMemberPullDTO1.setNotice_id(noticePullDTO.getNotice_id());
                        noticeMemberPullDTO1.setMember_id(id);
                        noticeMemberPullDTO1.setMember_name(name);
                        noticeMemberResource.addNoticeMemberInfo(noticeMemberPullDTO1);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }


        ResultDTO resultDTO = new ResultDTO();

        String QUERY = "";

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());

        //更新sql语句
        QUERY += "update notice set notice_updatetime ='" + time + "'";
        if (null != noticePullDTO.getNotice_title() && !"".equals(noticePullDTO.getNotice_title())) {
            QUERY += ", notice_title = '" + noticePullDTO.getNotice_title() + "'";
        }

        if (null != noticePullDTO.getNotice_type_id() && !"".equals(noticePullDTO.getNotice_type_id())) {
            QUERY += ",notice_type_id ='" + noticePullDTO.getNotice_type_id() + "'";
        }

        if (null != noticePullDTO.getRangeorganization_id() && !"".equals(noticePullDTO.getRangeorganization_id())) {
            QUERY += ",rangeorganization_id ='" + noticePullDTO.getRangeorganization_id() + "'";
        }

        if (null != noticePullDTO.getNotice_starttime() && !"".equals(noticePullDTO.getNotice_starttime())) {
            QUERY += ",notice_starttime ='" + noticePullDTO.getNotice_starttime() + "'";
        }
        if (null != noticePullDTO.getNotice_endtime() && !"".equals(noticePullDTO.getNotice_endtime())) {
            QUERY += ",notice_endtime ='" + noticePullDTO.getNotice_endtime() + "'";
        }

        if (null != noticePullDTO.getIssendnotify() && !"".equals(noticePullDTO.getIssendnotify())) {
            QUERY += ",issendnotify ='" + noticePullDTO.getIssendnotify() + "'";
        }
        if (null != noticePullDTO.getIstop() && !"".equals(noticePullDTO.getIstop())) {
            QUERY += ",istop ='" + noticePullDTO.getIstop() + "'";
        }

        if (null != noticePullDTO.getNotice_toptime() && !"".equals(noticePullDTO.getNotice_toptime())) {
            QUERY += ",notice_toptime ='" + noticePullDTO.getNotice_toptime() + "'";
        }
        if (null != noticePullDTO.getAttachment_id() && !"".equals(noticePullDTO.getAttachment_id()) && null != noticePullDTO.getFilestream() && !"".equals(noticePullDTO.getFilestream())) {
            //调用修改文件方法
            updateImage(noticePullDTO);
        } else if (null != noticePullDTO.getFilestream() && !"".equals(noticePullDTO.getFilestream())) {
            String uid = getImage(noticePullDTO)[0];
            QUERY += ",attachment_id='" + uid + "'";

        }
        if (null != noticePullDTO.getNotice_main() && !"".equals(noticePullDTO.getNotice_main())) {
            QUERY += ",notice_main ='" + noticePullDTO.getNotice_main() + "'";
        }
        if (null != noticePullDTO.getNotice_html() && !"".equals(noticePullDTO.getNotice_html())) {
            String html = replaceimage(noticePullDTO);

            QUERY += ",notice_html ='" + html + "'";
        }
        if (null != noticePullDTO.getSys_role_id() && !"".equals(noticePullDTO.getSys_role_id())) {
            QUERY += ",sys_role_id ='" + noticePullDTO.getSys_role_id() + "'";
        }
        if (null != noticePullDTO.getNotice_types() && !"".equals(noticePullDTO.getNotice_types())) {
            QUERY += ",notice_types ='" + noticePullDTO.getNotice_types() + "'";
        }
        if (null != noticePullDTO.getFail_resource() && !"".equals(noticePullDTO.getFail_resource())) {
            QUERY += ",fail_resource ='" + noticePullDTO.getFail_resource() + "'";
        }

        QUERY += " where notice_id = '" + noticePullDTO.getNotice_id() + "'";


        int result = this.addReportingTo(QUERY);
        // 判断SQl是否执行成功
        if (result != 0) {
            resultDTO.setStr(noticePullDTO.getNotice_id());
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.update_success);
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.update_fail);
        }
        return resultDTO;
    }


    //消息通知删除
    @Override
    public ResultDTO deleteNoticeInfo(NoticePullDTO noticePullDTO) {

        //删除之前查询是否有记录
        String sql = "select count(1) from notice where notice_id ='" + noticePullDTO.getNotice_id() + "'";

        String existName = getReportingToOne(sql);

        int result = 0;

        ResultDTO resultDTO = new ResultDTO();

        if (!existName.equals("0")) {

            String QUERY = "";
            QUERY += "delete from notice where notice_id='" + noticePullDTO.getNotice_id() + "'";

            result = this.addReportingTo(QUERY);
        }

        if (result != 0) {

            NoticeMemberPullDTO noticeMemberPullDTO = new NoticeMemberPullDTO();
            noticeMemberPullDTO.setNotice_id(noticePullDTO.getNotice_id());
            noticeMemberResource.deleteNoticeMemberInfo(noticeMemberPullDTO);

            WorkFlowPullDTO workFlowPullDTO = new WorkFlowPullDTO();
            workFlowPullDTO.setWork_flow_formid(noticePullDTO.getNotice_id());
            workFlowResource.deleteWorkFlowInfo(workFlowPullDTO);

            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.delete_success);
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.delete_fail);
        }
        return resultDTO;
    }



    /**
     * 保存图片方法
     *
     * @param
     * @return
     */
    public String[] getImage(NoticePullDTO noticePullDTO) {
        String str[] = new String[2];

        ResultDTO resultDTO = new ResultDTO();
        // TODO Auto-generated method stub
        String enpenform_image = "";
        //获取配置图片地址
        String[] image_path = this.getImage_path();
        String image_pathAddr = image_path[1];//服务器项目目录地址
        String image_pathSerAddr = image_path[2];//图片访问地址
        String imgDirct = image_pathAddr + "/notice";
        File f = new File(imgDirct);
        if (!f.exists()) {
            f.mkdirs();
            f.setWritable(true, false);
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

        String imgPath = imgDirct + "/" + noticePullDTO.getFile_type();


        //base64字符串保存为图片
        boolean headImg = FileProcess.GenerateImage(noticePullDTO.getFilestream(), imgPath);
        FileProcess.newlog("执行头像图片储存方法，储存照片地址：" + imgPath + " 方法返回：" + headImg);
        int resultls = 0;
        int mresult = 0;

        String imgurl = "/notice/" + noticePullDTO.getFile_type();

        //ArrayList<HeadPortaitDTO> result = new ArrayList<HeadPortaitDTO>();

        if (headImg) {
            //插入头像表
            enpenform_image += "insert into attachment(attachment_id,attachment_addr,head_portrait_time,file_type,file_name) values ('" + uuid + "','" + imgurl + "','" + df.format(new Date()) + "','" + noticePullDTO.getFile_type() + "','" + noticePullDTO.getFile_name() + "')";
            // enpenform_image += "insert into file(file_id,file_addr,file_time,filegui_id,file_name) values ('" + uuid + "','" +imgurl+ "','" +df.format(new Date()) + "','" + dataDTO.getFilegui_id() + "','" + dataDTO.getFiletype() + "')";
            //执行sql
            resultls = addReportingTo(enpenform_image);
        }

        if (resultls != 0) {
            str[0] = uuid;
            str[1] = imgurl;
            return str;
        }
        return null;
    }

    /**
     * 修改图片方法
     *
     * @param
     * @return
     */
    public String updateImage(NoticePullDTO noticePullDTO) {
        // TODO Auto-generated method stub
        String enpenform_image = "";
        //获取配置图片地址
        String[] image_path = this.getImage_path();
        String image_pathAddr = image_path[1];//服务器项目目录地址
        String image_pathSerAddr = image_path[2];//图片访问地址
        String imgDirct = image_pathAddr + "/notice";
        File f = new File(imgDirct);
        if (!f.exists()) {
            f.mkdirs();
            f.setWritable(true, false);
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

        String imgPath = imgDirct + "/" + noticePullDTO.getFile_type();

        //base64字符串保存为图片
        boolean headImg = FileProcess.GenerateImage(noticePullDTO.getFilestream(), imgPath);
        FileProcess.newlog("执行头像图片储存方法，储存照片地址：" + imgPath + " 方法返回：" + headImg);
        int resultls = 0;
        int mresult = 0;

        String imgurl = "/notice/" + noticePullDTO.getFile_type();

        //ArrayList<HeadPortaitDTO> result = new ArrayList<HeadPortaitDTO>();

        if (headImg) {
            //修改头像表
            enpenform_image += "update attachment set attachment_addr='" + imgurl + "',head_portrait_time = '" + df.format(new Date()) + "',file_type = '" + noticePullDTO.getFile_type() + "',file_name = '" + noticePullDTO.getFile_name() + "' where attachment_id='" + noticePullDTO.getAttachment_id() + "'";
            // enpenform_image += "insert into attachment(attachment_id,attachment_addr,head_portrait_time) values ('" + uuid + "','" + imgurl + "','" + df.format(new Date()) + "')";
            //执行sql
            resultls = addReportingTo(enpenform_image);
        }


        if (resultls != 0) {
            return uuid;
        }
        return null;
    }

}
